package top.haijunit.work.core.redis;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.format.FastDateFormat;
import cn.hutool.core.text.CharSequenceUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 【说明类功能】
 *
 * @author zhanghaijun
 * @since 2024-09-04
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class GenerateId {

    /**
     * 生成全局的唯一ID
     * 生成规则，{10}{6} 一共16位
     * <p>
     * 第一部分：{10} 年月日 yyMMddHHmm
     * 第二部分：{6} 原子序列
     */
    public String generateId() {
        return generateId(null);
    }

    public String generateId(String name) {
        String time = FastDateFormat.getInstance("yyMMddHHmm").format(new DateTime());
        return time + sequentialNo(CharSequenceUtil.blankToDefault(name, "uuid:global"), 6);
    }

    public String sequentialNo(String keyName, Integer targetLength) {
        long incr = RedissonUtils.incrAtomicValue(keyName);
        String incrStr = Long.toString(incr);
        int zeroCount = targetLength - incrStr.length();
        if (zeroCount <= 0) {
            return incrStr;
        }
        return "0".repeat(zeroCount) + incr;
    }
}
